package com.hzbank.game.mini.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.annotation.Resource;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hzbank.game.mini.model.ReturnT;
import com.hzbank.game.mini.service.BackgroundService;

@Controller
@RequestMapping("/background")
public class BackgroundController {
	
	@Resource
	BackgroundService backgroundService;
	
	@RequestMapping("/uploadFile")
	@ResponseBody
	public ReturnT<String> uploadFile(MultipartFile multipartFile) {
		String path = System.getProperty("user.dir");
		File file = new File(path+"\\"+System.currentTimeMillis()+".png");
		try {
			multipartFile.transferTo(file);
			return backgroundService.mergeIMG(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return new ReturnT<>(ReturnT.FAIL_CODE, "文件转换错误", e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			return new ReturnT<>(ReturnT.FAIL_CODE, "文件转换错误", e.getMessage());
		}
	}
	
	@RequestMapping("/uploadCode")
	@ResponseBody
	public ReturnT<String> uploadCode(String code) {
		return backgroundService.dealCode(code);
	}
	
	@RequestMapping("/getSignedIMG")
	@ResponseBody
	public ReturnT<String> getSignedIMG() {
		try {
            String filePath = System.getProperty("user.dir") + "\\img\\background.png";
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return new ReturnT<>(Base64.encodeBase64String(b));
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnT<>(ReturnT.FAIL_CODE, "获取背景图出错", e.getMessage());
        }
		
	}
}
